#include "SysCall.h"
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>

devSta GetEthLinkState()
{
    char output[128] = {0};
    FILE* stream = popen("ping 192.168.1.1 -c 1 -f -W 300 | grep -E \"[0-1] packets received\"", "r");
    fread(output, sizeof(char), sizeof(output), stream);
    pclose(stream);
    int recvPkt = -1;
    sscanf(output, "1 packets transmitted, %d packets received", &recvPkt);

    return (recvPkt == 1) ? DEVSTA_ETH_ONLINE : DEVSTA_ETH_OFFLINE;
}

const char* GetEthDelayMicrosec()
{
    static char ethDelayMicrosec[128] = {0};
    FILE* stream = popen("ping 192.168.1.1 -c 1 -f -W 300 | grep \"round-trip\" | awk '{print $4}' | awk -F '/' '{print $1}' | xargs echo -n", "r");
    fread(ethDelayMicrosec, sizeof(char), sizeof(ethDelayMicrosec), stream);
    pclose(stream);

    return ethDelayMicrosec;
}

const char* GetEthIP()
{
    static char ethIpAddr[128] = {0};
    FILE* stream = popen("ifconfig -a|grep inet|grep -v 127.0.0.1|grep -v inet6|awk '{print $2}'|tr -d \"addr:\" | xargs echo -n", "r");
    fread(ethIpAddr, sizeof(char), sizeof(ethIpAddr), stream);
    pclose(stream);

    return ethIpAddr;
}

// miiocli耗时较久，需要阻塞运行
void ToggleSwitch()
{
    static uint8_t workshopSwitch = 0;
    workshopSwitch ^= 1;
    printf("workshop %s", workshopSwitch == 1 ? "pwr on" : "pwr off");
    // in cli:
    //      sudo pip3 install python-miio --target=/usr/bin -i https://pypi.tuna.tsinghua.edu.cn/simple
    //      sudo nano /usr/lib/python3/dist-packages/my.pth
    //      add and save：/home/raii/.local/lib/python3.8/site-packages
    //      sudo /home/raii/.local/bin/miiocli device --ip 192.168.3.5 --token 21f7d80a678cf92131d879b37d1e78f3  raw_command set_properties "[{'did':'575499557','value':True,'siid':2,'piid':1}]"
    system(workshopSwitch ?
        "/home/raii/.local/bin/miiocli device --ip 192.168.1.10 --token 21f7d80a678cf92131d879b37d1e78f3  raw_command set_properties \"[{'did':'575499557','value':True,'siid':2,'piid':1}]\""
        :
        "/home/raii/.local/bin/miiocli device --ip 192.168.1.10 --token 21f7d80a678cf92131d879b37d1e78f3  raw_command set_properties \"[{'did':'575499557','value':False,'siid':2,'piid':1}]\"");
}
